<template>
  <n-form
    ref="formRef"
    :model="formValue"
    :rules="rules"
    label-placement="left"
  >
    <n-form-item label="旧密码" path="oldPassWord">
      <n-input
        v-model:value="formValue.oldPassWord"
        type="password"
        show-password-on="click"
        placeholder="输入密码"
      />
    </n-form-item>
    <n-form-item label="新密码" path="newPassWord">
      <n-input
        v-model:value="formValue.newPassWord"
        type="password"
        show-password-on="click"
        placeholder="输入密码"
      />
    </n-form-item>
    <n-form-item>
      <n-button attr-type="button" @click="handleValidateClick">
        提交
      </n-button>
    </n-form-item>
  </n-form>
</template>

<script setup lang="ts">
import {
  type FormInst,
  type FormItemRule,
  type FormRules,
  NInput,
  NForm,
  NFormItem,
  NButton,
} from "naive-ui";
import { updatePassword, type UpdateUserPassWordDto } from "~/api/user";

const formValue = ref<UpdateUserPassWordDto>({
  oldPassWord: "",
  newPassWord: "",
});
const formRef = ref<FormInst | null>(null);
function validatePasswordSame(rule: FormItemRule, value: string): boolean {
  return value !== formValue.value.oldPassWord;
}
const rules: FormRules = {
  oldPassWord: [
    {
      required: true,
      message: "请输入旧密码",
    },
  ],
  newPassWord: [
    {
      required: true,
      message: "请输入新密码",
      trigger: ["input", "blur"],
    },
    {
      pattern:
        /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/,
      message:
        "密码应包含数字、大小写字母、特殊符号中的3类、且长度大于8、小于16、",
      trigger: ["input", "blur"],
    },
    {
      validator: validatePasswordSame,
      message: "旧密码和新密码输入不能一致",
      trigger: ["blur", "password-input"],
    },
  ],
};
const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      await updatePassword(formValue.value);
    } else {
      naiveui.message.error(errors[0][0].message ?? "表单验证错误");
    }
  });
};
</script>
<style scoped></style>
